package cn.engage.pet.service.impl;

import cn.engage.RocketMQ.Util.RocketMqProducer;
import cn.engage.basic.config.BussinessException;
import cn.engage.basic.domain.Point;
import cn.engage.basic.service.impl.BaseServiceImpl;
import cn.engage.basic.util.*;
import cn.engage.order.domain.OrderPetAcquisition;
import cn.engage.order.service.OrderPetAcquisitionService;
import cn.engage.org.domain.Employee;
import cn.engage.org.domain.Shop;
import cn.engage.org.mapper.EmployeeMapper;
import cn.engage.org.mapper.ShopMapper;
import cn.engage.pet.domain.SearchMasterMsg;
import cn.engage.pet.domain.SearchMasterMsgAuditLog;
import cn.engage.pet.dto.AcceptDto;
import cn.engage.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.engage.pet.mapper.SearchMasterMsgMapper;
import cn.engage.pet.query.SearchMasterMsgQuery;
import cn.engage.pet.service.SearchMasterMsgService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author engage
 * @since 2022-11-01
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements SearchMasterMsgService {
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionService orderPetAcquisitionService;
    @Autowired
    private RocketMqProducer rocketMqProducer;

    /* 用户填写寻主信息保存到数据库 */
    @Override
    public AjaxResult publish(SearchMasterMsg searchMasterMsg) {
        // 先保存到数据库
        searchMasterMsgMapper.add(searchMasterMsg);

        // 进行参数的校验
        ParameterVerification(searchMasterMsg);

        // 百度ai进行检验
        BaiduAICheck(searchMasterMsg);

        // 成功则寻找50公里内最近的店铺
        Point point = DistanceUtil.getPoint(searchMasterMsg.getAddress());
        List<Shop> shops = shopMapper.findAll();
        Shop shop = DistanceUtil.getNearestShop(point, shops);
        if (shop != null){
            searchMasterMsg.setShopId(shop.getId());
            searchMasterMsg.setState(1);
            searchMasterMsgMapper.update(searchMasterMsg);
        }
        return AjaxResult.me().success();
    }
    /* 审核页面列表展示 */
    @Override
    public PageList<SearchMasterMsg> findSearchMsgQuery(SearchMasterMsgQuery query) {
        // 查询条数
        Integer totals = searchMasterMsgMapper.findSearchMsgQueryByCount(query);
        if (null == totals || 0 == totals){
            return new PageList<>(0,new ArrayList<>());
        }
        // 查询数据
        List<SearchMasterMsg> searchMasterMsgs = searchMasterMsgMapper.findSearchMsgQuery(query);

        //方到返回里面
        return new PageList<SearchMasterMsg>(totals,searchMasterMsgs);
    }
    /* 接收订单 */
    @Override
    public void accept(AcceptDto acceptDto) {
        // 根据前端传入的id查询是否有该寻主信息
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findByIdOne(acceptDto.getMsgId());
        if (searchMasterMsg == null){
                throw new BussinessException("没有该寻主信息!");
        }
        // 加同步锁保证线程安全防止几个用户同时修改数据的情况
        synchronized (searchMasterMsg.getId()){
            Employee employee = employeeMapper.findByIdOne(acceptDto.getHandler());
            if (employee == null){
                    throw new BussinessException("没有该员工!");
                }
                if (searchMasterMsg.getState() == 1 && searchMasterMsg.getShopId().equals(employee.getShopId())){
                    // 修改状态未2(表示已接单)
                    searchMasterMsg.setState(2);
                    searchMasterMsgMapper.update(searchMasterMsg);
                    // 生成订单保存到数据库
                    initOrderPetAcquisition(acceptDto, searchMasterMsg, employee);
                }
        }
    }
    /* 拒绝订单 */
    @Override
    public void reject(Long msgId, Employee employee) {
        // 查询该寻主信息
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findByIdOne(msgId);
        // 如果为空抛出异常
        if (searchMasterMsg == null){
            throw new BussinessException("寻主消息为空!");
        }
        // 不为空,将shopId置空
        searchMasterMsg.setShopId(null);
        searchMasterMsgMapper.update(searchMasterMsg);
        /* 保存拒单日志 */
    }

    // 百度AI校验参数
    private void BaiduAICheck(SearchMasterMsg searchMasterMsg) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(searchMasterMsg.getTitle())
                .append(",")
                .append(searchMasterMsg.getCoatColor())
                .append(",")
                .append(searchMasterMsg.getName());
        // 审核不通过保存错误信息
        if (!BaiduAuditUtils.TextCensor(String.valueOf(stringBuilder))){
            SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
            searchMasterMsgAuditLog.setMsgId(searchMasterMsg.getId());
            searchMasterMsgAuditLog.setNote("含有不合格字符串");
            searchMasterMsgAuditLogMapper.add(searchMasterMsgAuditLog);
            throw new BussinessException("含有不合格字符串,审核失败，请去个人中心修改");
        }
    }
    // 进行参数的校验
    private void ParameterVerification(SearchMasterMsg searchMasterMsg) {
             // 如果宠物姓名和地址为空则提示不能为空，
        if (StringUtils.isBlank(searchMasterMsg.getAddress()) || StringUtils.isBlank(searchMasterMsg.getName()) ||
                searchMasterMsg.getPrice() == null){
            // 保存失败日志
            SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
            searchMasterMsgAuditLog.setMsgId(searchMasterMsg.getId());
            searchMasterMsgAuditLog.setNote("参数为空");
            searchMasterMsgAuditLogMapper.add(searchMasterMsgAuditLog);
            throw new BussinessException("参数不能为空,审核失败,请去个人中心更改");
        }
    }
    // 生成订单
    private void initOrderPetAcquisition(AcceptDto acceptDto, SearchMasterMsg searchMasterMsg, Employee employee) {
        OrderPetAcquisition orderPetAcquisition = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(acceptDto.getHandler());
        orderPetAcquisition.setOrderSn(orderSn);
        orderPetAcquisition.setDigest(acceptDto.getNote());
        orderPetAcquisition.setLastConfirmTime(new Date(System.currentTimeMillis() + 3 * 24 * 60 * 60 * 1000));
        orderPetAcquisition.setState(0);
        // 此時的钱就是用户发布的价格，要注意此金额不是最终金额，要以实际交易金额为准
        orderPetAcquisition.setPrice(new BigDecimal(searchMasterMsg.getPrice()));
        orderPetAcquisition.setUserId(searchMasterMsg.getUserId());
        orderPetAcquisition.setShopId(employee.getShopId());
        orderPetAcquisition.setAddress(searchMasterMsg.getAddress());
        orderPetAcquisition.setEmpId(employee.getId());
        orderPetAcquisition.setSearchMasterMsgId(searchMasterMsg.getId());
        orderPetAcquisitionService.add(orderPetAcquisition);

        rocketMqProducer.sendDelayMsg(orderSn, 3);
    }


}
